package com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.service;

import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.service.RfidCodeDetailService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.guize.entity.SalesDelivery.SalesDelivery;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.guize.entity.SalesDelivery.SalesDeliveryDetails;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.LocationEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.mapper.LocationMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service.LocationEntityService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.entity.RepickStock;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.mapper.RePickMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.model.Repick.RepickDetailsDto;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.pandian.model.Repick.RepickListDto;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.EpcEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.TaglistEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.mapper.impl.EpclistMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.TaglistService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class RePickService {
    @Autowired
    LocationEntityService locationEntityService;
    @Autowired
    RePickMapperImpl rePickMapper;
    @Autowired
    BaseService baseService;
    @Autowired
    LocationMapperImpl locationMapper;
    @Autowired
    RfidCodeDetailService rfidCodeDetailService;
    @Autowired
    TaglistService taglistService;

    @Autowired
    EpclistMapperImpl tempEpclistMapper;


    /**
     * 获取单据所有信息
     *
     * @param orderCode 单据code
     * @param pageBegin 开始页面
     * @param pageSize  页面尺寸
     * @return 返回查询结果
     */
    public DataResult GetRepickOrderList(String orderCode, int pageBegin, int pageSize, String tenant_id) {
        DataResult dataResult = new DataResult(0, "查询失败");
        try {
            int total = 0;
            List<RepickListDto> dto = rePickMapper.GetRepickList(orderCode, pageBegin, pageSize, tenant_id);
            total = rePickMapper.GetRepickListCount(orderCode, pageBegin, pageSize, tenant_id);
            dataResult.setStatus(1);
            dataResult.setMessage("查询成功");
            dataResult.setDataList(dto);
            dataResult.setTotalSize(total);
            return dataResult;
        } catch (Exception e) {

            dataResult.setMessage(e.toString());
            return dataResult;
        }

    }

    /**
     * 获取反捡货单据的详情
     * 支持返拣到其他仓库
     *
     * @param orderId 单据Id
     * @return
     */
    public DataResult GetRepickDetails(String orderId, String tenant_id) throws Exception {
        DataResult dataResult = new DataResult(1, "查询成功");
        List<RepickDetailsDto> repickDetailsDtoList = rePickMapper.GetRepickDetails(orderId, tenant_id);
        List<String> epcList = repickDetailsDtoList.stream().map(it -> it.getRfidCode()).distinct().collect(Collectors.toList());
        List<TaglistEntity> taglistEntities = taglistService.SelectByEpcs(epcList, tenant_id);
        for (RepickDetailsDto item : repickDetailsDtoList) {
            List<LocationEntity> allLocation = locationMapper.getLocationByWId(item.getWarehouseId(), tenant_id);
            List<LocationEntity> NallLocation = locationMapper.getLocationByWId(item.getNwarehouseId(), tenant_id);
            String locationName = LocationEntityService.GetLocationFullNameEx(item.getLocationId(), allLocation, "");
            String NlocationName = LocationEntityService.GetLocationFullNameEx(item.getNlocationId(), NallLocation, "");
            item.setLocationName(locationName);
            item.setNlocationname(NlocationName);
            TaglistEntity tagEntity = taglistEntities.stream().filter(it -> it.getCoderfid().equals(item.getRfidCode())).findAny().orElse(null);
            if (tagEntity != null) item.setTagName(tagEntity.getName());
        }
        dataResult.setDataList(repickDetailsDtoList);
        return dataResult;
    }

    /**
     * 返拣接口
     * by chen
     *
     * @param id
     * @param localID
     * @param recodeId
     * @param modifier
     * @param tenant_id
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public DataResult UpdatePickStatus(String id, String localID, String recodeId, String modifier, String tenant_id) throws Exception {
        DataResult dataResult = new DataResult(0, "反拣数据更新失败");
        if (StringUtils.isEmpty(id) || StringUtils.isEmpty(localID)) {
            dataResult = new DataResult(0, "参数错误!");
            return dataResult;
        }
        // 对扫描到的标签进行去重操作 防止数量比对出现问题
        List<String> ids = Arrays.asList(id.split(",")).stream()
                .filter(it -> !it.isEmpty()).distinct().collect(Collectors.toList());
        if (ids.size() == 0) return dataResult;
        // 修改epc数据信息
        LocationEntity location = locationEntityService.getLocationById(localID, tenant_id);
        if (location == null) return dataResult;
        String huojiaID = LocationEntityService.GetHuojiaIDByEntity(location, tenant_id);


        List<EpcEntity> epcEntityList = tempEpclistMapper.selectByIds(ids, tenant_id);
        for (EpcEntity item : epcEntityList) {
            item.setShelf_id(huojiaID);
            item.setLocation_id(location.getId());
            item.setWarehouse_id(location.getWarehouse_id());
            item.setWarehouse_code(location.getWarehouse_code());
            item.setModifier(modifier);
            item.setRfid_status(1);
        }
        int rInt = tempEpclistMapper.editForShangjia(epcEntityList, tenant_id);
        // 查询已返拣数量
        int repickStockCount = 0;
        List<RepickStock> RepickStockDetailList = rePickMapper.GetRepickCountByStatus(recodeId, tenant_id);
        if (RepickStockDetailList != null) {
            repickStockCount = RepickStockDetailList.size() + ids.size();
        }
        System.out.println("查询已返拣数量" + repickStockCount);
        // 更新表的状态 反捡状态 0未反捡 1反捡中 2已反捡 3到货单未拣货弃审(没有反拣明细)
        int repickstatus = 0;
        List<RepickDetailsDto> repickDetailsDtoList = rePickMapper.GetRepickDetails(recodeId, tenant_id);
        if (repickDetailsDtoList.size() == 0) {
            repickstatus = 3;
        } else if (repickDetailsDtoList.size() > repickStockCount) {
            repickstatus = 1;
        } else if (repickDetailsDtoList.size() == repickStockCount) {
            repickstatus = 2;
        }
        System.out.println("应返拣数量" + repickDetailsDtoList.size());
        // 更新返拣数据的反捡状态 成功更新的数量
        int updateStatus = rePickMapper.UpdateRepickStatus(ids, recodeId, tenant_id);
        // 软删除拣货记录
        int updatestorerecord = rePickMapper.Updatestorerecord(ids, recodeId, tenant_id);
        // 更新发货通知单返拣状态
        int updateOrder = rePickMapper.UpdateRepickOrderStatus(recodeId, repickstatus);
        if (updateOrder == 0) {
            dataResult.setMessage("单据返拣状态更新失败");
            return dataResult;
        }
        dataResult.setStatus(1);
        dataResult.setMessage("更新成功");

        return dataResult;
    }

    /**
     * 根据捡获记录查询出所有需要填写入反捡记录的数据
     *
     * @param salesDelivery        发货单主表解析信息
     * @param salesDeliveryDetails 发货单详情
     * @return 返回所有回写记录
     */
    public int InsertStoreRecodeByOrderIdAndPId(String tenant_id, SalesDelivery salesDelivery, List<SalesDeliveryDetails> salesDeliveryDetails) {
        int resultCount = 0;

        List<RepickStock> repickStockList = new ArrayList<>();
        for (SalesDeliveryDetails item : salesDeliveryDetails) {
            List<RepickStock> repickStocks = new ArrayList<>();
            repickStocks = rePickMapper.RepickDetailByOrderIdAndPId(salesDelivery.getId(), item.getId(), tenant_id);
            for (RepickStock repickStockitem : repickStocks
            ) {
                repickStockitem.setOrderDetailId(item.getId());
                repickStockitem.setProductId(item.getProductId());
                repickStockitem.setProductname(item.getProductName());
                repickStockitem.setProductSkuId(item.getSkuId());
                repickStockitem.setProductSkuName(item.getSkuName());
                repickStockitem.setOrderId(salesDelivery.getId());
                repickStockitem.setOrderCode(salesDelivery.getCode());
                repickStockitem.setCreateor(salesDelivery.getCreator());
                repickStockitem.setTenant_id(tenant_id);
                repickStockList.add(repickStockitem);
            }
        }
        if (repickStockList.size() > 0) {
            resultCount = rePickMapper.InsertRepickStock(repickStockList);
        } else {
            // 需要将单据状态变成已反捡
            int updateOrder = rePickMapper.UpdateRepickOrderStatus(salesDelivery.getId(), 3);
        }
        return resultCount;
    }

    /**
     * 单据审核后 修改详单的状态
     *
     * @return 返回更新条数
     */
    public int UpdateRepickDrStatus(String orderId, String tenant_id) {
        int result = rePickMapper.UpdateRepickStockDrStatus(orderId, tenant_id);
        return 0;
    }
}
